<script lang="ts" setup>
import { reactive, ref, onMounted, watch, nextTick } from 'vue'
import {
  post,
  saveToLocalStore,
  loadLocalStore,
  removeToLocalStore,
  encryptRSA,
  decryptRSA,
  loginSuccess,
} from '@/common/index'
import type { FormInstance, FormRules } from 'element-plus'
import { User, Lock, Right, Back } from '@element-plus/icons-vue'
import type { RuleForm, UserInfo, rememberType } from '@/types/user.ts'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import slideVerification from '@/components/slideVerification.vue'
const route = useRoute()
const router = useRouter()
import { useUserStore } from '@/stores'
const userInfo = useUserStore()
const dialogTableVisible = ref(false) // 滑动验证弹窗
const sliderFlag = ref(false) // 滑动验证弹窗
const ruleLoginForm = reactive<RuleForm>({
  userName: '',
  password: '',
  rePassword: '',
  phone: '',
  code: '',
})
// 定义用户的信息
// const userInfo = ref<UserInfo>({
//   userName: '',
//   password: '',
//   phone: '',
//   id: 0,
//   avatar: '',
//   createTime: '',
//   updateTime: '',
//   roles: [],
//   routes: [],
//   token: ''
// })
const ruleLoginFormRef = ref<FormInstance>()
const ruleRegisterFormRef = ref<FormInstance>()
// 定义一个正则表达式，用于检查密码是否符合要求
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/ // 至少8个字符，包含大小写字母、数字和特殊字符
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入正确的密码'))
  } else if (!passwordRegex.test(value)) {
    callback(new Error('请输入至少8个字符，包含大小写字母、数字和特殊字符的密码')) // 密码不符合要求
  } else {
    // if (ruleLoginForm.password !== '') {
    //   // if (!ruleLoginFormRef.value) return
    //   // ruleLoginFormRef.value.validateField('password', () => undefined)
    // }
    callback()
  }
}
const LoginRules = reactive<FormRules<RuleForm>>({
  userName: [
    { required: true, message: '请输入正确的用户名', trigger: 'blur' },
    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
  ],
  password: [
    {
      // required: true, message: '请输入正确的密码', trigger: 'blur'
      // pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/, message: '至少8个字符，包含大小写字母、数字和特殊字符', trigger: 'blur'
      required: true,
      validator: validatePass,
      trigger: 'blur',
    },
  ],
  rePassword: [
    {
      // required: true, message: '请再次输入正确密码', trigger: 'blur'
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        //两次输入的密码不一致
        if (value === '') {
          callback(new Error('请输入正确的密码'))
        } else if (value !== ruleLoginForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  phone: [
    {
      required: true,
      message: '请输入正确的手机号',
      trigger: 'blur',
      pattern: /^1[3456789]\d{9}$/,
    },
  ],
  code: [
    {
      required: true,
      message: '请输入正确的验证码',
      trigger: 'blur',
      pattern: /^\d{6}$/,
    },
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  // formEl.resetFields(); //重置表单
  validateCode.value = true
  await formEl.validate((valid, fields) => {
    console.log(valid, fields)
    if (valid) {
      // console.log('submit!')
      if (ruleLoginFormRef.value) {
        post('login', { userName: ruleLoginForm.userName, password: ruleLoginForm.password })
          .then((res) => {
            console.log(res)
            // 登录成功
            if (res.data.code == 200) {
              // 记住密码
              if (remember.value) {
                //记住密码
                const rememberLogin = {
                  userName: ruleLoginForm.userName,
                  password: encryptRSA(ruleLoginForm.password),
                  remember: true,
                }
                saveToLocalStore('rememberLogin', rememberLogin)
              } else {
                removeToLocalStore('rememberLogin')
              }

              // 登录成功
              // userInfo.setToken(res.data.token) //保存token
              // userInfo.setUserInfo(res.data.userInfo)
              // saveToLocalStore("token", res.data.data.token);
              // userInfo.value= Object.assign(userInfo.value, res.data.data.userInfo);
              // if(userInfo.value.password) {
              //   userInfo.value.password = decryptRSA(userInfo.value.password);
              // }
              formEl.resetFields() //重置表单
              ElMessage({
                message: '登录成功',
                type: 'success',
              })
              // 登录成功后跳转
              loginSuccess()
              //从定向登录之后往哪里跳转
              const redirect: any = route.query.redirect || '/home'
              router.push({ path: redirect })
            }
          })
          .catch((err) => {
            console.log(err)
            formEl.resetFields() //重置表单
          })
      } else {
        if (!serious.value) {
          ElMessage({
            message: '请勾选同意协议',
            type: 'warning',
          })
          serious.value = true

          return
        }
        //加一个滑动验证码
        dialogTableVisible.value = true
        if (sliderFlag.value) {
          post('/register', {
            phone: ruleLoginForm.phone,
            password: ruleLoginForm.password,
            code: ruleLoginForm.code,
          })
            .then((res) => {
              console.log(res)
              if (res.data.code == 200) {
                ElMessage({
                  message: '注册成功',
                  type: 'success',
                })
                // 两种情况，一是跳转登录页
                isRegister.value = true
                // 而是直接登录，跳转首页
                // 登录成功
                // saveToLocalStore("token", res.data.data.token);
                // userInfo.value= Object.assign(userInfo.value, res.data.data.userInfo);
                // if(userInfo.value.password) {
                //   userInfo.value.password = decryptRSA(userInfo.value.password);
                // }
                // router.push({ path: '/home' });
              }
            })
            .catch((err) => {
              console.log(err)
            })
        }
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
const isRegister = ref(true)
const SMS = ref<boolean>(true)

onMounted(() => {
  console.log('父组件', isRegister.value)
})
watch(isRegister, (newValue) => {
  ruleLoginForm.userName = ''
  ruleLoginForm.password = ''
  ruleLoginForm.rePassword = ''
  ruleLoginForm.phone = ''
})

const showPassword = ref<boolean>(true)

const sendCodeText = ref<string>('发送验证码')
const sendFlag = ref<boolean>(true)
const registerSMS = ref<FormInstance>()
const serious = ref<boolean>(false)
const validateCode = ref<boolean>(true) //是否要校验验证码
//点击发送验证码
const sendCode = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  validateCode.value = false
  await formEl.validate((valid, fields) => {
    if (valid) {
      sendFlag.value = false
      let time = 60
      let timer = setInterval(() => {
        time--
        sendCodeText.value = time + 's后重新发送' //修改按钮文字
        if (time <= 0) {
          clearInterval(timer)
          sendFlag.value = true
          // validateCode.value = true;
          sendCodeText.value = '发送验证码'
        }
      }, 1000)
      post('sendCode', { phone: ruleLoginForm.phone })
        .then((res) => {
          console.log(res)
        })
        .catch((err) => {
          console.log(err)
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const remember = ref<boolean>(false)
// 取消记住密码
const checkRemember = () => {
  if (!remember.value) removeToLocalStore('rememberLogin')
}
const remem = () => {
  togglePW.value = !togglePW
  SMS.value = true
  isRegister.value = false
}
const isRe=()=>{
  isRegister.value = !isRegister
  togglePW.value = false
}
//获取记住密码
onMounted(() => {
  // console.log('demo',typeof encryptRSA('123456'),decryptRSA(encryptRSA('123456')));
  // console.log('rememberLogin',typeof loadLocalStore("rememberLogin").password,decryptRSA(loadLocalStore("rememberLogin").password));
  if (loadLocalStore('rememberLogin')) {
    ruleLoginForm.userName = loadLocalStore('rememberLogin').userName
    ruleLoginForm.password = decryptRSA(loadLocalStore('rememberLogin').password)
    remember.value = true
  }
})

const togglePW = ref<boolean>(false)
</script>

<template>
  <el-row>
    <el-col :span="12" class="bg" :xs="{ span: 10, offset: 0 }"></el-col>
    <el-col :span="6" :offset="3" class="form" :xs="{ span: 12, offset: 1 }" :lg="{ span: 5, offset: 3.5 }">
      <!-- 登录 -->
      <el-form ref="ruleLoginFormRef" :model="ruleLoginForm" :rules="LoginRules" size="large" autocomplete="off"
        v-if="isRegister" class="form">
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="userName">
          <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="ruleLoginForm.userName" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input :prefix-icon="Lock" :show-password="showPassword" placeholder="请输入密码"
            v-model="ruleLoginForm.password" type="password" />
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox v-model="remember" @change="checkRemember">记住我</el-checkbox>
            <el-link type="primary" :underline="false" @click="
              remem
            ">忘记密码?</el-link>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleLoginFormRef)" style="width: 100%">登录</el-button>
        </el-form-item>
        <el-form-item>
          <el-link :underline="false" class="link" @click="isRe">注册<el-icon>
              <Right />
            </el-icon></el-link>
        </el-form-item>
      </el-form>
      <!-- 注册 -->
      <el-form ref="ruleRegisterFormRef" :model="ruleLoginForm" size="large" :rules="LoginRules" autocomplete="off"
        v-if="!isRegister && !SMS" class="form">
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="userName">
          <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="ruleLoginForm.userName" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input :prefix-icon="Lock" placeholder="请输入密码" type="password" v-model="ruleLoginForm.password" />
        </el-form-item>
        <el-form-item prop="rePassword">
          <el-input :prefix-icon="Lock" placeholder="请再次输入密码" type="password" v-model="ruleLoginForm.rePassword" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleRegisterFormRef)">注册</el-button>
        </el-form-item>
        <el-form-item>
          <el-link :underline="false" class="link" @click="isRegister = !isRegister"><el-icon>
              <Back />
            </el-icon>登录</el-link>
        </el-form-item>
      </el-form>
      <!-- 短信注册/找回密码 -->
      <el-form :model="ruleLoginForm" :rules="LoginRules" ref="registerSMS" class="form" v-if="!isRegister && SMS">
        <el-form-item>
          <h1>{{ togglePW ? '找回密码' : '注册' }}</h1>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input placeholder="请输入手机号" v-model="ruleLoginForm.phone" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input :prefix-icon="Lock" :show-password="showPassword" placeholder="请输入密码"
            v-model="ruleLoginForm.password" type="password" />
        </el-form-item>
        <el-form-item>
          <el-col :span="12">
            <el-form-item :prop="validateCode ? 'code' : ''">
              <el-input placeholder="6位验证码" v-model="ruleLoginForm.code" />
            </el-form-item>
          </el-col>
          <el-col :span="9" :offset="3">
            <el-button type="default" class="senBtn" @click="sendCode(registerSMS)" v-if="sendFlag">{{ sendCodeText
              }}</el-button>
            <div class="senBtn" v-else>{{ sendCodeText }}</div>
          </el-col>
        </el-form-item>

        <el-form-item>
          <div class="checkbox">
            <el-checkbox v-model="serious"><span class="gray">我已认真阅读并接受 </span></el-checkbox>
            <el-link type="primary" :underline="false">服务协议、隐私政策</el-link>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="senBtn" @click="submitForm(registerSMS)">{{
            togglePW ? '确定修改' : '注册'
            }}</el-button>
        </el-form-item>
        <el-form-item>
          <el-form-item>
            <span class="el-checkbox">已有账号,</span>
            <el-link type="primary" :underline="false" @click="isRegister = !isRegister">直接登录</el-link>
          </el-form-item>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
  <!-- <el-button :plain="true"></el-button> -->
  <slide-verification v-model:dialogTableVisible="dialogTableVisible"
    v-model:sliderFlag="sliderFlag"></slide-verification>
</template>
<style lang="scss" scoped>
.el-row {
  flex-wrap: nowrap;
}

.link:hover {
  color: inherit;
}

.bg {
  background: rgba(172, 162, 221, 0.3);
  height: 100vh;
  border-radius: 0 50px 50px 0;
}

.gray {
  color: gray;
}

.flex {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.senBtn {
  width: 100%;
  text-align: center;
}

.form {
  max-width: 400px;
  min-width: 320px;
}

.checkbox {
  display: flex;

  .el-checkbox {
    margin-right: 8px;
  }
}
</style>
